package com.da.demo.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-02-24
 * @Version: 1.0
 */
@Component
@Slf4j
public class CaptChaFilter extends OncePerRequestFilter {
    /**
     * 该方法为过滤器的核心逻辑，用于处理每个请求。
     * 它会检查请求的 URI 是否为 /user/login，如果是，则验证验证码。
     * 如果验证码验证通过，则继续处理请求；否则，重定向到根路径。
     *
     * @param request     当前的 HTTP 请求对象
     * @param response    当前的 HTTP 响应对象
     * @param filterChain 过滤器链，用于将请求传递给下一个过滤器或目标资源
     * @throws ServletException 如果在处理请求过程中发生 Servlet 相关的异常
     * @throws IOException      如果在处理请求过程中发生 I/O 异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestUri = request.getRequestURI();
        log.info("Before processing: {}", requestUri);

        String code = request.getParameter("captcha");
        String sessionCode = (String) request.getSession().getAttribute("captcha");

        if (requestUri.equals("/user/login")) {
            if (!StringUtils.hasText(code)) {
                log.info("Captcha is missing, redirecting to root");
                response.sendRedirect("/");
            } else if (!code.equalsIgnoreCase(sessionCode)) {
                log.info("Captcha does not match, redirecting to root");
                response.sendRedirect("/");
            } else {
                log.info("Captcha verification passed, continue the request");
                filterChain.doFilter(request, response);
            }
        } else {
            log.info("Request URI is not /user/login, passing through");
            filterChain.doFilter(request, response);
        }

        log.info("After processing: {}", request.getRequestURI());
    }
}
